#!/usr/bin/env python
# coding: utf-8

import sys

reload(sys)
sys.setdefaultencoding('utf-8')
import datetime
from flask import Flask, request, jsonify, render_template
from werkzeug.utils import secure_filename
from scpy.logger import get_logger
from SCAWS import *
import copy

app = Flask(__name__)
logger = get_logger(__file__)

s3 = S3()

check_update_codes = """#!/bin/sh
set -e
aws s3 sync {s3_address} /usr/app/
cd /usr/app/
tar -zxf *.tar.gz
rm -rf *.tar.gz
cd /usr/app/{app_name}/{start_file_path}
{pip_requirement}
for k in $(seq 1 {process_num} )
 do
    nohup {enviroment} {start_file_name} 1>/dev/null 2>/dev/null &
 done
"""

DEFAULT_ENV = '/usr/bin/python'

@app.before_request
def before_start():
    logger.info(request.url + ' ' + request.method + '')


@app.route('/')
def index():
    return 'hello world'


@app.route('/deploy', methods=['GET', 'POST'])
def deploy():
    if request.method == 'GET':
        return render_template('deploy.html')
    else:
        form = request.form
        instances_name = form.get('instance_name', '')
        s3_url = '/'.join(form.get('s3_addr', '').split('/')[:-1])
        app_name = form.get('app_name', '')
        start_file_name = form.get('start_file_name', '')
        start_file_path = form.get('start_file_path', '')
        image_id = form.get('image_id', '')
        instance_num = form.get('instance_num', '')
        process_num = form.get('process_num', '')
        enviroment = form.get('enviroment', DEFAULT_ENV)
        if enviroment == DEFAULT_ENV:
            pip_requirement = 'pip install -r requirements.txt'
        else:
            pip_requirement = ''
        if request.files:
            content = request.files['file'].read()
            key = 'crawler/{app_name}/{date}/code/{filename}'.format(
                app_name=app_name,
                date=datetime.datetime.today().strftime('%Y/%m/%d'),
                filename=secure_filename(request.files['file'].filename)
            )
            s3.upload_file('sc-resource', key, content)
            s3_url = 's3://sc-resource/' + key
        check_update_code = check_update_codes.format(
            s3_address=s3_url,
            app_name=app_name,
            start_file_name=start_file_name,
            start_file_path=start_file_path,
            process_num=process_num,
            pip_requirement = pip_requirement,
            enviroment = enviroment
        )

        try:
            aws = EC2()
            aws.create_instances(
                instances_name=instances_name, image_id=image_id, max_count=int(instance_num),
                user_data=check_update_code
            )
        except Exception, e:
            logger.exception(e)
            return render_template('deploy.html', message='应用: %s 初始化失败. 错误信息: %s' % (app_name, e))
        return render_template('deploy.html', message='应用: %s 初始化成功' % app_name)


@app.route('/get_s3_url')
def get_s3_url():
    term = request.args.get('term', '')
    bucket = request.args.get('bucket', '')
    if bucket:
        data = s3.list_files(bucket)
        iter_data = data
        data = []
        for item in iter_data:
            if 'tar.gz' in item.get('Key',''):
                data.append(item)
        return jsonify({
            'data': data
        })
    buckets = s3.list_buckets()
    data = []
    if term == '':
        data = buckets
    else:
        for item in buckets:
            print item.get('Name', '')
            if term in item.get('Name', ''):
                data.append({
                    'id': item.get('Name', ''),
                    'label': item.get('Name', ''),
                    'value': item.get('Name', '')
                })
    return jsonify({
        'data': data
    })


@app.route('/terminate',methods=['POST'])
def terminate():
    aws = EC2()
    name = request.form.get('name', '')
    ids = request.form.get('instancesId', '')
    if name:
        aws.terminate_instances(by_tag_name=name)
    elif ids:
        aws.terminate_instances(by_ids=[])
    else:
        return '参数不正确'
    return ''

@app.route('/get_ec2_tags')
def get_tags():
    aws = EC2()
    results = aws.list_tags()
    results = list(set([item.get('Value','') for item in results]))
    return jsonify({
        'data':results
    })


if __name__ == '__main__':
    app.debug = True
    app.run()
